<template>
    <el-card style="width:800px;">
        <div class="mem_tit">修改商品</div>
            <div style="font-size: 20px;cursor:pointer" >
                <i @click="back" class="el-icon-back"></i>
            </div>
        <el-form  title="添加商品" :model="form" status-icon :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
            <el-form-item label="商品名称" prop="name">
                <el-input type="text" v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
                <el-input type="text" :rows="10" v-model="form.price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商品库存" prop="stock">
                <el-input type="text" :rows="10" v-model="form.stock" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商品类型">
                <el-select v-model="form.categoryLevelIds" @remove-tag="removeTag" @change="changeOption" multiple placeholder="请选择">
                    <el-option
                    v-for="item in options"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品图片" >
                <input type="hidden" v-model="form.fileName"/>
                <el-upload
                    name="file"
                    class="upload-demo"
                    accept="image/jpg,image/jpeg,image/gif,image/png"
                    action="/easybuy/products/uploadPic"
                    :on-success="handleSuccess"
                    :on-remove="handleRemove"
                    :before-upload="boforeUpload"
                    list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg/gif文件，且不超过5MB</div>
                </el-upload>
            </el-form-item>

            <el-form-item label="商品描述" prop="description">
                <el-input type="textarea" :rows="5" v-model="form.description" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('form')">提交</el-button>
                <el-button @click="resetForm('form')">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>

</template>

<script>
export default {
    name:'ProductsEdit',
    data:function(){
        return{
            categories:[],
            options:[],
             form:{
                name:'',
                description:'',
                price:'',
                stock:'',
                categoryLevelIds:[],
                fileName:'',
            },
            rules:{
                name:[{required:true,message:'请填写商品名称',trigger:'blur'}],
                description:[{required:true,message:'请填写商品描述信息',trigger:'blur'}],
                price:[{required:true,message:'请填写商品价格',trigger:'blur'},{pattern:/^(?:[1-9]\d*|0)(?:\.\d+)?$/,message:'价格必须大于0',trigger:'blur'}],
                stock:[{required:true,message:'请填写商品库存',trigger:'blur'},{pattern:/^[1-9]\d*$/,message:'库存必须为正整数',trigger:'blur'}],

            }
        }
    },
    mounted(){
        //获取商品信息
        this.backData();
        //获取一级分类的数据
        this.optionsByParentId(0);
    },
     methods:{
        //数据回显
        backData(){
          this.$axios({
            url:'/easybuy/products/edit/'+this.$route.params.id,
          }).then(rs=>{
            console.log(rs.data.data);
            let product = rs.data.data;
            this.form.name = product.name;
            this.form.price = product.price;
            this.form.description = product.description;
            this.form.stock = product.stock;
            this.form.fileName = product.fileName;
            this.form.categoryLevelIds = [
              product.categoryLevel1Id,
              product.categoryLevel2Id,
              product.categoryLevel3Id
            ].filter(id => id); // 过滤掉空值，避免有 null
          })
        },
        //移除所选内容后的回调方法
        removeTag(removedId){
            // console.log("remove:",removedId);
            let index = this.categories.indexOf(removedId);
            // console.log("index:",index);
            this.form.categoryLevelIds.splice(index);
            this.categories.splice(index);
            this.changeOption(this.form.categoryLevelIds);
        },
        //分类选择的内容变化时
        changeOption(ids){
            // console.log("ids",ids);
            if(ids.length >= 1){
                this.optionsByParentId(ids[ids.length-1]);
            }else{
                this.optionsByParentId(0);
            }
            if(ids.length > this.categories.length){
                this.categories.push(ids[ids.length-1]);
            }
            
        },
        //文件上传成功后的回调
        handleSuccess(responose,file,fileList){
            this.$message.success('文件上传成功！');
            this.form.fileName = responose.fileName;
        },
        //移除文件的回调函数
        handleRemove(file,fileList){
            this.$axios({
                url:'/easybuy/products/removePic',
                params:{
                    fileName:this.form.fileName
                }
            }).then(rs=>{
                console.log(rs);
                if(rs.data.code == 200){
                    this.$message.success('移除文件成功！')
                }
            })
        },
        boforeUpload(file, fileList) {
            console.log(file, fileList);
            const types = ['image/jpeg','image/jpg','image/jpg','image/gif'];
            const maxSize = 5*1024*1024;
            let flag = false;
            for(let i=0;i<types.length;i++){
                if(file.type == types[i]){
                    flag = true;
                }
            }
            if(!flag){
                this.$message.error('文件类型错误！');
                return false;
            }
            if(file.size > maxSize){
                this.$message.error("文件大小超过限制，只能上传5MB以内的文件");
                return false;
            }
        },
        handlePreview(file) {
            console.log("preview",file);
        },
        //返回分页展示页面
        back(){
            this.$router.push({name:'BackProducts'});
        },
        submitForm(formName) {
            console.log(this.$ref);
            this.$refs[formName].validate((valid) => {
            if (valid) {
                console.log(this);
               this.edit(
                    this.$route.params.id,
                    this.form.name,this.form.description,
                    this.form.price,this.form.stock,this.form.fileName,
                    this.form.categoryLevelIds
               );
            } else {
                console.log('请填写完整信息!!');
                return false;
            }
            });
      },
    resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //添加商品信息
    edit(id,name,description,price,stock,fileName,categoryLevelIds){
        this.$axios({
            method:"post",
            url:'/easybuy/products/edit',
            data:{
                id,
                name,
                description,
                price,
                stock,
                fileName,
                isDelete:0,
                categoryLevelIds
            }
        }).then(rs=>{
            if(rs.data.code == 200){
                this.$message.success("修改成功!");
                this.$router.replace({path:'/back-index/back-products'});
            }else{
                this.$message.error("服务器错误!");
            }
        })
    },
    optionsByParentId(parentId){
        this.$axios({
            url:'/easybuy/category/'+parentId
        }).then(rs=>{
            console.log(rs);
            this.options = rs.data.categoryList;
        })
    }
    },
}
</script>

<style>

</style>